import 'dart:async';

import 'package:flutter/material.dart';

class CountdownTimer {
  ValueNotifier<int> timeLeft;
  Timer? _timer;

  CountdownTimer(int seconds) : timeLeft = ValueNotifier<int>(seconds);

  void startTimer() {
    _timer?.cancel(); // 确保开始前，任何旧的定时器被取消
    _timer = Timer.periodic(const Duration(seconds: 1), (_) {
      if (timeLeft.value > 0) {
        timeLeft.value--;
      } else {
        _timer?.cancel();
      }
    });
  }

  void dispose() {
    _timer?.cancel();
    timeLeft.dispose();
  }
}

class CountdownPageExample extends StatefulWidget {
  const CountdownPageExample({super.key});

  @override
  State<CountdownPageExample> createState() => _CountdownPageExampleState();
}

class _CountdownPageExampleState extends State<CountdownPageExample> {
  late CountdownTimer countdownTimer;

  @override
  void initState() {
    super.initState();
    countdownTimer = CountdownTimer(10); // 设置为10秒倒计时
    countdownTimer.startTimer();
  }

  @override
  void dispose() {
    countdownTimer.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Countdown Timer')),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Center(
              child: ValueListenableBuilder<int>(
                valueListenable:
                    countdownTimer.timeLeft, // 监听CountdownTimer实例的timeLeft
                builder: (context, value, child) {
                  return Text('倒计时: $value秒');
                },
              ),
            ),
            for (int i = 0; i < 100; i++) Text('ListTile: $i'),
          ],
        ),
      ),
    );
  }
}
